// pages/buy-lesson/buy-lesson.js
import {validatePhoneNumber, validateAge} from '../../utils/util.js'
var app = getApp()
Page({

    /**
     * Page initial data
     */
    data: {
        name: "",
        phoneNumber: "",
        age: "",
		lessons: "",
		selectLessons: null

    },
    /**
     * Lifecycle function--Called when page load
     */
    onLoad(options) {
        console.log(options.lesson)
        this.setData(
            {
                name: '',
                phoneNumber: '',
                age: "",
				lessons: options.lesson,
				totalPrice: app.gettotalprice()
            }
		)
		var orgInfo = app.getorginfo()
        if (orgInfo) {
			var lessonSelectList = []
			var all_lessons = this.data.lessons.split('_')
			for (var i = 0; i < all_lessons.length; i++) {
				var lesson_details = all_lessons[i].split('.')
				var orgIdx = parseInt(lesson_details[0]) - 1
				var lessonIdx = parseInt(lesson_details[1])
				var name = ""
				for (var j = 0; j < orgInfo[orgIdx].lessons.length; j++) {
					if (orgInfo[orgIdx].lessons[j].id == lessonIdx) {
						name = orgInfo[orgIdx].lessons[j].name
						break
					}
				}
				var lessonSelectOne = {
					"icon": orgInfo[orgIdx].icon,
					"orgName":orgInfo[orgIdx].title,
					"name": name
				}
				lessonSelectList.push(lessonSelectOne)
			}
			this.setData(
				{
					"selectLessons": lessonSelectList
				}
			)
		} else {
			wx.reLaunch({
              	url: '../index/index',
			})
		}
    },

    /**
     * Lifecycle function--Called when page is initially rendered
     */
    onReady() {

    },

    /**
     * Lifecycle function--Called when page show
     */
    onShow() {

    },

    /**
     * Lifecycle function--Called when page hide
     */
    onHide() {

    },

    /**
     * Lifecycle function--Called when page unload
     */
    onUnload() {

    },

    /**
     * Page event handler function--Called when user drop down
     */
    onPullDownRefresh() {

    },

    /**
     * Called when page reach bottom
     */
    onReachBottom() {

    },

    /**
     * Called when user click on the top right corner to share
     */
    onShareAppMessage() {

    },
    changeName(e) {
        if (e.detail.value != "") {
            this.data.name = e.detail.value
        }
    },
    changeAge(e) {
        console.log(e)
        if (e.detail.value != "") {
            this.data.age = e.detail.value
        }
    },
    changePhone(e) {
        if (e.detail.value != "") {
            this.data.phoneNumber = e.detail.value
        }
    },
    onBuyLesson(e) {
        if (this.data.name == "") {
            wx.showToast({
              title: '请输入幼儿姓名'
            })
            return
        }
        if (this.data.age == "" || !validateAge(this.data.age)) {
            wx.showToast({
                title: '请输入正确的幼儿年龄',
                icon:'none'
            })
            return
        }
        if (!validatePhoneNumber(this.data.phoneNumber)) {
            wx.showToast({
                title: '手机号码不正确'
              })
              return
        }
        console.log(this.data.phoneNumber)
        console.log(this.data.name)
        console.log(this.data.age)
        var openid = app.getopenid()
        if (!openid) {
            wx.showToast({
                title: '登录已过期，请重新登录',
                icon: 'none',
                duration: 1000
              })
            setTimeout(function() {
                wx.reLaunch({
                    url: '../index/index'
                })
            }, 1000)
            return
        }
        var that = this
        wx.request({
            url: app.globalData.BASE_URL + '/mallUserBuy',
            method: 'POST',
            data: {
                userId:openid,
                lessons:this.data.lessons,
                originUserId: app.globalData.scene,
                childName: this.data.name,
                childAge: this.data.age,
                childPhone: this.data.phoneNumber
            },
            success(res) {
                if (res.statusCode != 200) {
                    wx.showToast({
                      title: '服务器忙，请稍后再试',
                      icon: 'none'
                    })
                    return
                } else {
                    console.log(res)
                    if (res.data && res.data.error != 0) {
                        wx.showToast({
                            title: '每个用户最多只能\n买一次课程',
                            icon:'none'
                          })
                        setTimeout(function() {
                            wx.redirectTo({
                                url: '../index/index'
                            })
                          }, 1000)
                        return
                    }
                    if (res.data) {
                        that.executeBuy(res.data)
                    } else {
                        wx.showToast({
                            title: '服务器忙, 请稍后再试',
                            icon:'none'
                          })
                        setTimeout(function() {
                            wx.redirectTo({
                                url: '../index/index'
                            })
                          }, 1000)
                    }
                }
            },
            fail(rr) {
                console.log(rr)
            }
          })
    },
    executeBuy(info) {
        wx.requestPayment({
          nonceStr: info.nonceStr,
          package: info.packageVal,
          paySign: info.paySign,
          timeStamp: info.timeStamp,
          signType: 'RSA',
          success(res) {
            wx.showToast({
                title: '购买成功',
                icon: 'none',
                duration: 1000
              })
            setTimeout(function() {
                wx.reLaunch({
                    url: '../index/index'
                })
            }, 1000)
          },
          fail(res) {
          }
        })
    }
})